package com.store.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.store.entity.User;
import com.store.mapper.EmployeePerformanceMapper;
import com.store.mapper.UserMapper;
import com.store.vo.PerformanceVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 业绩服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PerformanceService {
    
    private final EmployeePerformanceMapper performanceMapper;
    private final UserMapper userMapper;
    
    /**
     * 获取员工业绩统计
     */
    public PerformanceVO getEmployeePerformance(Long employeeId, LocalDate startDate, LocalDate endDate) {
        // 验证员工
        User employee = userMapper.selectById(employeeId);
        if (employee == null) {
            throw new RuntimeException("员工不存在");
        }
        if (!"employee".equals(employee.getRole())) {
            throw new RuntimeException("该用户不是员工");
        }
        
        PerformanceVO vo = new PerformanceVO();
        vo.setEmployeeId(employeeId);
        vo.setEmployeeName(employee.getName());
        vo.setStartDate(startDate);
        vo.setEndDate(endDate);
        
        // 统计业绩
        Map<String, Object> stats;
        if (startDate != null && endDate != null) {
            stats = performanceMapper.selectPerformanceByDateRange(employeeId, startDate, endDate);
        } else {
            stats = performanceMapper.selectTotalPerformance(employeeId);
        }
        
        vo.setTotalOrders(getIntValue(stats.get("totalOrders")));
        vo.setTotalSales(getBigDecimalValue(stats.get("totalSales")));
        vo.setTotalRefunds(getBigDecimalValue(stats.get("totalRefunds")));
        vo.setTotalNetSales(getBigDecimalValue(stats.get("totalNetSales")));
        
        // 获取趋势数据
        if (startDate != null && endDate != null) {
            List<Map<String, Object>> trendData = performanceMapper.selectPerformanceTrend(
                    employeeId, startDate, endDate
            );
            
            List<PerformanceVO.PerformanceTrendItem> trend = trendData.stream()
                    .map(this::convertToTrendItem)
                    .collect(Collectors.toList());
            vo.setTrend(trend);
        }
        
        return vo;
    }
    
    /**
     * 获取员工总业绩
     */
    public PerformanceVO getEmployeeTotalPerformance(Long employeeId) {
        return getEmployeePerformance(employeeId, null, null);
    }
    
    /**
     * 获取员工本月业绩
     */
    public PerformanceVO getEmployeeMonthPerformance(Long employeeId) {
        LocalDate now = LocalDate.now();
        LocalDate startDate = now.withDayOfMonth(1);
        LocalDate endDate = now;
        return getEmployeePerformance(employeeId, startDate, endDate);
    }
    
    /**
     * 转换趋势数据项
     */
    private PerformanceVO.PerformanceTrendItem convertToTrendItem(Map<String, Object> data) {
        PerformanceVO.PerformanceTrendItem item = new PerformanceVO.PerformanceTrendItem();
        
        Object dateObj = data.get("date");
        if (dateObj instanceof LocalDate) {
            item.setDate((LocalDate) dateObj);
        } else if (dateObj instanceof java.sql.Date) {
            item.setDate(((java.sql.Date) dateObj).toLocalDate());
        }
        
        item.setOrderCount(getIntValue(data.get("orderCount")));
        item.setSalesAmount(getBigDecimalValue(data.get("salesAmount")));
        item.setRefundAmount(getBigDecimalValue(data.get("refundAmount")));
        item.setNetSales(getBigDecimalValue(data.get("netSales")));
        
        return item;
    }
    
    /**
     * 获取Integer值
     */
    private Integer getIntValue(Object value) {
        if (value == null) {
            return 0;
        }
        if (value instanceof Integer) {
            return (Integer) value;
        }
        if (value instanceof Long) {
            return ((Long) value).intValue();
        }
        if (value instanceof BigDecimal) {
            return ((BigDecimal) value).intValue();
        }
        return 0;
    }
    
    /**
     * 获取BigDecimal值
     */
    private BigDecimal getBigDecimalValue(Object value) {
        if (value == null) {
            return BigDecimal.ZERO;
        }
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }
        if (value instanceof Double) {
            return BigDecimal.valueOf((Double) value);
        }
        if (value instanceof Integer) {
            return BigDecimal.valueOf((Integer) value);
        }
        if (value instanceof Long) {
            return BigDecimal.valueOf((Long) value);
        }
        return BigDecimal.ZERO;
    }
}




